package com.dd.cloud.user.service.chknowl.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.ExtUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.admin.AdminSaleInfo;
import com.dd.cloud.user.entity.chknowl.ChknowlChVideo;
import com.dd.cloud.user.entity.chknowl.ChknowlChVideoChapter;
import com.dd.cloud.user.entity.chknowl.ChnowlChVideoCategory;
import com.dd.cloud.user.mapper.chknowl.ChknowlChVideoChapterMapper;
import com.dd.cloud.user.mapper.chknowl.ChknowlChVideoMapper;
import com.dd.cloud.user.req.chknowl.ChkonwlVideoReq;
import com.dd.cloud.user.req.chknowl.ExcelAddVideoModel;
import com.dd.cloud.user.req.chknowl.ExcelChknowlVoideModel;
import com.dd.cloud.user.service.chknowl.IChknowlChVideoChapterService;
import com.dd.cloud.user.service.chknowl.IChknowlChVideoService;
import com.dd.cloud.user.service.chknowl.IChnowlChVideoCategoryService;
import com.dd.cloud.user.service.chknowl.IChnowlVideoRecordService;
import com.dd.cloud.user.service.file.IFileInfoService;
import com.dd.cloud.user.util.HuaWeiOBSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.req.chknowl.*;
import com.dd.cloud.user.res.chknowl.ChknowlConsiliaPageRes;
import com.dd.cloud.user.req.chknowl.ChkonwlVideoReq;
import com.dd.cloud.user.req.chknowl.ExcelAddVideoModel;
import com.dd.cloud.user.req.chknowl.ExcelChknowlVoideModel;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 书院课程表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2023-10-12
 */
@Service
@Slf4j
public class ChknowlChVideoServiceImpl extends ServiceImpl<ChknowlChVideoMapper, ChknowlChVideo> implements IChknowlChVideoService {

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private IChknowlChVideoChapterService chknowlChVideoChapterService;

    @Autowired
    private IChnowlVideoRecordService chnowlVideoRecordService;

    @Autowired
    private ChknowlChVideoChapterMapper chknowlChVideoChapterMapper;


    @Autowired
    private IChnowlChVideoCategoryService chnowlChVideoCategoryService;


    /**
     * 我的课程
     */
    @Override
    public IPage<ChknowlChVideo> chknowlChVideoService(ChkonwlVideoReq chkonwlVideoReq) {
        IPage<ChknowlChVideo> iPage = chkonwlVideoReq.pagePojo();
        iPage = getBaseMapper().chknowlChVideoService(iPage, chkonwlVideoReq);
        return iPage;
    }


    @Override
    public ChknowlChVideo queryVideoById(Integer id) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        ChknowlChVideo chknowlChVideo = this.getById(id);
        if (chknowlChVideo != null) {
            List<ChknowlChVideoChapter> chknowlChVideoChapterList = chknowlChVideoChapterMapper.queryVideoListById(id, loginInfo.getId());
            chknowlChVideo.setChknowlChVideoChapterList(chknowlChVideoChapterList);
        }
        return chknowlChVideo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importVideoBatch(MultipartFile file) {
        List<ExcelAddVideoModel> list;
        try {
            if (file == null) {
                throw new ZekeException("请上传文件");
            }
            list = ExtUtils.importExcel(file, 0, 1, ExcelAddVideoModel.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException("解析Excel失败");
        }
        if (list == null || list.isEmpty()) {
            throw new ZekeException("数据为空");
        }
        List<ChknowlChVideo> list1 = new ArrayList<>();
        for (ExcelAddVideoModel videoModel : list) {
            String title = videoModel.getTitle();
            String[] strs = title.split("-");
            title = strs[0].replace("《", "").replace("》", "").trim();
            ChknowlChVideo chknowlChVideo = new ChknowlChVideo();
            chknowlChVideo.setName(videoModel.getTitle())
                    .setIntroductory(videoModel.getDescribe())
//                    .setSort(videoModel.getSort())
                    .setStatus(1).setCreateDate(LocalDateTime.now())
                    .setTitle(title).setSchool(strs[1]).setAuthor(strs[2]);
            list1.add(chknowlChVideo);
        }
        if (CollectionUtil.isNotEmpty(list1)) {
            boolean flag = this.saveBatch(list1);
            if (!flag) {
                throw new ZekeException("~保存失败~");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBookUrlBatch(MultipartFile file) {
        List<ExcelChknowlVoideModel> list;
        try {
            if (file == null) {
                throw new ZekeException("请上传文件");
            }
            list = ExtUtils.importExcel(file, 0, 1, ExcelChknowlVoideModel.class, true);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException("解析Excel失败");
        }
        if (list == null || list.isEmpty()) {
            throw new ZekeException("数据为空");
        }
        List<ChknowlChVideoChapter> videoList = new ArrayList<>();
        List<ExcelChknowlVoideModel> models = list.stream().filter(item -> "标清".equals(item.getTs())).collect(Collectors.toList());
        for (ExcelChknowlVoideModel model : models) {
            String name = model.getName();
            String[] strArrays = name.split("_");
            LambdaQueryWrapper<ChknowlChVideo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChknowlChVideo::getName, strArrays[0].trim())
                    .eq(ChknowlChVideo::getStatus, 1);
            List<ChknowlChVideo> chknowlChVideos = this.list(wrapper);
            if (chknowlChVideos.size() != 1) {
                log.info("~课程搜索错误~" + strArrays[0].trim());
                continue;
            }
            ChknowlChVideo chknowlChVideo = chknowlChVideos.get(0);
            Integer videoId = chknowlChVideo.getId();
            ChknowlChVideoChapter chknowlChVideoChapter = new ChknowlChVideoChapter();
            if (strArrays.length == 2) {
                String strArray = strArrays[0].trim();
                String sort = strArrays[1].trim();
                log.info("课程名称名字:{}", strArray);
                log.info("序号为:{}", sort);
                chknowlChVideoChapter.setName(strArray).setSort(Integer.valueOf(sort));
            } else if (strArrays.length == 3) {
                String strArray = strArrays[0].trim();
                String chapterName = strArrays[1].trim();
                String sort = strArrays[2].trim();
                log.info("课程名称名字:{}", strArray);
                log.info("小节名称名字:{}", chapterName);
                log.info("序号为:{}", sort);
                chknowlChVideoChapter.setName(chapterName).setSort(Integer.valueOf(sort));
            }
            chknowlChVideoChapter.setChapterUrl(model.getUrl()).setVideoId(videoId).setStatus(1).setCreatedDate(LocalDateTime.now());
            videoList.add(chknowlChVideoChapter);
        }
        if (CollectionUtil.isNotEmpty(videoList)) {
            boolean flag = chknowlChVideoChapterService.saveBatch(videoList);
            if (!flag) {
                throw new ZekeException("保存课程路径失败");
            }
        }
    }

    @Override
    public void updateVideoNum(Integer videoId) {
        ChknowlChVideo chknowlChVideo = this.getById(videoId);
        if (chknowlChVideo != null) {
            chknowlChVideo.setNum(chknowlChVideo.getNum() + 1);
            this.updateById(chknowlChVideo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importVideoImgBatch(MultipartFile[] files) {
        List<ChknowlChVideo> list = new ArrayList<>();
        for (int j = 0; j < files.length; j++) {
            MultipartFile file = files[j];
            String originalFilename = file.getOriginalFilename();
            String[] strs = originalFilename.split("\\.");
            if (strs.length != 2) {
                continue;
            }
            LambdaQueryWrapper<ChknowlChVideo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChknowlChVideo::getName, strs[0].trim())
                    .eq(ChknowlChVideo::getStatus, 1);
            ChknowlChVideo chknowlChVideo = this.getOne(wrapper);
            if (chknowlChVideo == null) {
                continue;
            }
            String bookUrl = HuaWeiOBSUtil.uploadFile(file);
            chknowlChVideo.setImgUrl(bookUrl);
            list.add(chknowlChVideo);
        }
        if (CollectionUtil.isNotEmpty(list)) {
            this.updateBatchById(list);
        }
    }

    @Override
    public List<ChnowlChVideoCategory> queryVideoCategoryList() {
        LambdaQueryWrapper<ChnowlChVideoCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChnowlChVideoCategory::getStatus, 1)
                .orderByDesc(ChnowlChVideoCategory::getCreateDate);
        List<ChnowlChVideoCategory> list = chnowlChVideoCategoryService.list(queryWrapper);
        return list;
    }

    @Override
    public void queryVideoTotalTime(MultipartFile file) {
        List<ExcelChknowlVoideModel> list;
        try {
            if (file == null) {
                throw new ZekeException("请上传文件");
            }
            list = ExtUtils.importExcel(file, 0, 1, ExcelChknowlVoideModel.class, true);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException("解析Excel失败");
        }
        if (list == null || list.isEmpty()) {
            throw new ZekeException("数据为空");
        }
        List<ExcelChknowlVoideModel> models = list.stream().filter(item -> "标清".equals(item.getTs())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(models)) {
            Map<String, List<ExcelChknowlVoideModel>> map = models.stream()
                    .filter(item -> !StringUtils.isEmpty(item.getCategory()))
                    .collect(Collectors.groupingBy(ExcelChknowlVoideModel::getCategory));
            for (String key : map.keySet()) {
                Integer totalSeconds = 0;
                List<ExcelChknowlVoideModel> modelList = map.get(key);
                if (CollectionUtil.isNotEmpty(modelList)) {
                    for (ExcelChknowlVoideModel model : modelList) {
                        try {
                            String time = model.getTime();
                            SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                            SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
                            Date parse = null;
                            parse = sdf1.parse(time);
                            String format = sdf2.format(parse);
                            Date timeDate = sdf2.parse(format);
                            Integer hours = timeDate.getHours();
                            Integer minutes = timeDate.getMinutes();
                            Integer seconds = timeDate.getSeconds();
                            totalSeconds = totalSeconds + (hours * 3600 + minutes * 60 + seconds);
                            log.info("小时:{},分:{},秒:{},总共时长:{}", hours, minutes, seconds, totalSeconds);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    ExcelChknowlVoideModel model = modelList.get(0);
                    String name = model.getName();
                    String[] strArrays = name.split("_");
                    String strArray = "";
                    if (strArrays.length == 2) {
                        strArray = strArrays[0].trim();
                        log.info("课程名称名字:{}", strArray);
                    } else if (strArrays.length == 3) {
                        strArray = strArrays[0].trim();
                        log.info("课程名称名字:{}", strArray);
                    }
                    LambdaQueryWrapper<ChknowlChVideo> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(ChknowlChVideo::getName, strArray).eq(ChknowlChVideo::getStatus, 1).last("limit 1");
                    ChknowlChVideo chknowlChVideo = this.getOne(queryWrapper);
                    if (chknowlChVideo != null) {
                        chknowlChVideo.setTotalTime(totalSeconds);
                        this.updateById(chknowlChVideo);
                    }
                }
            }
        }
    }


}
